const moment = require('moment');
const EventsEmitter = require('events');
const {randomNum} = require('../../../util/number');
const {client, apkSupporterCode, deviceCode} = require('../mqtt');

//发布订阅事件对象
const event = new EventsEmitter();

client.on('connect', () => {
    client.subscribe([`basic/${apkSupporterCode}/${deviceCode}`], {qos: 2}, err => {
        if (!err) {
            console.log(`设备开机`, `【basic/${apkSupporterCode}/${deviceCode}】订阅成功\n`)
        }
        event.emit("上行-basic主题订阅成功", {client});
    })
})

client.on('message', (topic, message) => {
    const msg = message.toString();
    if (msg) {
        const messageJson = JSON.parse(msg);
        console.log("↓", topic, "\n", JSON.stringify(messageJson, null, 4))
        if (topic === `basic/${apkSupporterCode}/${deviceCode}`) {
            event.emit("下行-订阅basic主题消息", {client, messageJson});
        } else if (topic.startsWith('thing/down/action/')) {
            event.emit("下行-指令消息", {client, messageJson});
        } else if (topic.startsWith('ntp/down/')) {
            event.emit("下行-NTP校时", {client, messageJson});
        } else if (topic.startsWith('ota/update/down/')) {
            event.emit("下行-OTA升级消息", {client, messageJson});
        } else if (topic.startsWith('error/')) {
            event.emit("下行-平台异常通知", {client, messageJson});
        } else {
            console.log(`↓message:\n${msg}`)
        }
    } else {
        console.error("平台下发消息为空")
    }
})

// -------事件处理--------
event.on("上行-basic主题订阅成功", data => {
    // 向主题 subscribe/report/${仪表apk定制开发商标识}/${deviceCode} 主题发布 订阅成功消息
    const {client} = data;
    const req = {}
    req.ts = moment().format('YYYYMMDDHHmmssSSS')
    req.traceId = deviceCode + '.' + moment().format('YYYYMMDDHHmmssSSS') + '.' + randomNum(6)
    req.deviceCode = deviceCode
    req.success = true
    req.errorMsg = ''
    const version = {launchAppVersion: '1.0.2'}
    req.data = {feedbackStage: '01', version, resolution: '1280*800'}
    const reqJsonStr = JSON.stringify(req)
    const topic = `subscribe/report/${apkSupporterCode}/${deviceCode}`;
    console.log(`${topic} 阶段一\n`, "↑", JSON.stringify(req, null, 4), '\n')
    client.publish(topic, reqJsonStr, {qos: 2});
});

event.on("下行-订阅basic主题消息", data => {
    const {client, messageJson} = data;
    if (messageJson.success) {
        const {traceId, data, res} = messageJson;
        const {toSubTopics} = data;
        const topics = {};
        for (let i = 0; i < toSubTopics.length; i++) {
            const subTopic = toSubTopics[i];
            topics[subTopic.topic] = {qos: subTopic.qos}
        }
        client.subscribe(topics, function (err) {
            if (!err) {
                console.log('平台下发的主题列表设备已成功订阅\n')
            }
            const {needRes, topic, qos} = res
            if (needRes) {
                const req = {}
                req.ts = moment().format('YYYYMMDDHHmmssSSS')
                req.traceId = traceId;
                req.deviceCode = deviceCode;
                req.success = true;
                req.errorMsg = ''
                req.data = {feedbackStage: '02'};
                const reqJsonStr = JSON.stringify(req)
                console.log(`${topic} 阶段二\n`, "↑ " + JSON.stringify(req, null, 4), '\n')
                client.publish(topic, reqJsonStr, {qos});
            }
        })
    } else {
        console.log('平台端业务异常返回：', messageJson.errorMsg)
    }
})

event.on("下行-指令消息", data => {
    const {client, messageJson} = data;
    if (messageJson.success) {
        const {traceId, productCode, sn, deviceCode, data, res} = messageJson;
        const {cmdType} = data
        const {needRes, topic, qos} = res
        if (needRes) {
            const req = {}
            req.ts = moment().format('YYYYMMDDHHmmssSSS')
            req.traceId = traceId;
            req.productCode = productCode;
            req.sn = sn;
            req.deviceCode = deviceCode;
            req.cmdSupport = true;
            req.success = true;
            req.errorMsg = '';
            req.data = {cmdType};
            const reqJsonStr = JSON.stringify(req)
            console.log("↑ " + JSON.stringify(req, null, 4), '\n')
            client.publish(topic, reqJsonStr, {qos});
        }
    } else {
        console.log('平台端业务异常返回：', messageJson.errorMsg)
    }
})

event.on("下行-NTP校时", data => {
    const {client, messageJson} = data;
    if (messageJson.success) {
        const {traceId, productCode, sn, deviceCode, data, res} = messageJson;
        const {needRes, topic, qos} = res
        if (needRes) {
            const {ntpTimeStamp} = data;
            console.log('平台系统时间 ', moment(ntpTimeStamp).format('YYYY-MM-DD HH:mm:ss'))
            const req = {}
            req.ts = moment().format('YYYYMMDDHHmmssSSS')
            req.traceId = traceId;
            req.productCode = productCode;
            req.sn = sn;
            req.deviceCode = deviceCode;
            req.success = true;
            req.errorMsg = '';
            req.data = {};
            const reqJsonStr = JSON.stringify(req)
            console.log("↑ " + JSON.stringify(req, null, 4), '\n')
            client.publish(topic, reqJsonStr, {qos});
        }
    } else {
        console.log('平台端业务异常返回：', messageJson.errorMsg)
    }
})

event.on("下行-OTA升级消息", data => {
    const {client, messageJson} = data;
    if (messageJson.success) {
        const {traceId, productCode, sn, deviceCode, data, res} = messageJson;
        const {needRes, topic, qos} = res
        if (needRes) {
            const {otaBatchId} = data;
            // 向主题 subscribe/report/${仪表apk定制开发商标识}/${deviceCode} 响应 订阅成功消息
            const req = {}
            req.ts = moment().format('YYYYMMDDHHmmssSSS')
            req.traceId = traceId;
            req.productCode = productCode;
            req.sn = sn;
            req.deviceCode = deviceCode;
            req.success = true;
            req.errorMsg = '';
            // updateUpStage: '01'  设备是否支持升级反馈
            req.data = {updateUpStage: '01', otaBatchId, isSupport: true, isUpdated: false, errorMsg: ''};
            // updateUpStage: '02'  升级包下载进度反馈
            // req.data = {updateUpStage: '02', otaBatchId, downloadPer: 50};
            // updateUpStage: '03'  升级包进入安装升级流程前反馈
            // req.data = {updateUpStage: '03', otaBatchId};
            // updateUpStage: '04'  升级结果反馈
            // req.data = {updateUpStage: '04', otaBatchId, updated: true, newVersion: "1.4.4", errorMsg: ""};
            const reqJsonStr = JSON.stringify(req)
            console.log("↑ " + JSON.stringify(req, null, 4), '\n')
            client.publish(topic, reqJsonStr, {qos});
        }
    } else {
        console.log('平台端业务异常返回：', messageJson.errorMsg)
    }
})

event.on("下行-平台异常通知", data => {
    const {messageJson} = data;
    console.log('平台异常通知：', messageJson)
})
